package com.supersit.greensproject.AsyncTask;

import android.content.Context;
import android.os.AsyncTask;
import android.os.Handler;
import android.os.Message;

import com.google.gson.Gson;
import com.supersit.greensproject.DB.XUtilsDbManager;
import com.supersit.greensproject.R;
import com.supersit.greensproject.entity.BaseBase;
import com.supersit.greensproject.resources.API;
import com.supersit.greensproject.utils.HttpXUtils;
import com.supersit.greensproject.utils.L;
import com.supersit.greensproject.utils.MyCallBack;
import com.supersit.greensproject.utils.T;
import com.supersit.greensproject.view.ShowDialog;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.DbManager;
import org.xutils.ex.DbException;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by Administrator on 2016/8/25 0025.
 */
public class UpLoadBaseBaseList {
    private static List<BaseBase> resultList = new ArrayList<>();
    private final int UPLOAD_SUCCESS = 0x01;
    private final int UPLOAD_FAIL = 0x02;
    private final int SERVICE_ERROR = 0x03;
    private final int JSON_DATA_ERROR = 0x04;
    private Context mContext;
    private ShowDialog showDialog;
    private UpdateResult mUpdateResult;
    private List<BaseBase> list;

    public UpLoadBaseBaseList(List<BaseBase> list, Context context, UpdateResult updateResult) {
        this.mContext = context;
        this.mUpdateResult = updateResult;
        this.list = list;
        showDialog = new ShowDialog(context);
    }

    public void uploadData() {
        String url = API.UploadBaseData;
        Map<String, Object> map = new HashMap<>();
        Gson gson = new Gson();
        String str = "{productionBaseInfo:" + gson.toJson(list) + "}";
        L.d("json:" + str);
        map.put("baseInfo", str);
        showDialog.showLoadingDialog("正在上传数据。。。");
        HttpXUtils.Post(url, map, new MyCallBack<String>() {
            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                showDialog.dismissLoadDialog();
                super.onError(ex, isOnCallback);
                Message message = new Message();
                message.what = SERVICE_ERROR;
                handler.sendMessage(message);
            }

            @Override
            public void onSuccess(String result) {
                showDialog.dismissLoadDialog();
                super.onSuccess(result);
                L.d("base synchorization result", result);
                List<BaseBase> list = new ArrayList<>();
                try {
                    JSONObject jsonObject = new JSONObject(result);
                    int isfalse = jsonObject.optInt("isfalse");
                    String msg = jsonObject.optString("msg");
                    if (isfalse == 1) {//1成功 0失敗
                        JSONArray jsonArray = jsonObject.optJSONArray("resultdata");
                        if (jsonArray.length() > 0) {
                            for (int i = 0; i < jsonArray.length(); i++) {
                                JSONObject item = jsonArray.optJSONObject(i);
                                String objectid = item.optString("objectid");
                                int baseId = item.optInt("id");
                                String jdnum = item.optString("jdnum");//基地编号
                                String baseName = item.optString("name");
                                String businessLicence = item.optString("no");//许可证
                                String address = item.optString("address");//地址
                                String productCategory = item.optString("productCategory");//pc用，android无用。
                                String area = item.optString("area");//pc用，android无用。
                                String type = item.optString("type");//基础类型中文字符串 pc用，android无用。
                                String contacts = item.optString("conname");//联系人
                                String tel = item.optString("tel");
                                String email = item.optString("email");
                                int flag = item.optInt("flag");//用地规划用的。现在无用
                                String cteatetime = item.optString("createtime");//上报基地时间 无用
                                int isDelete = item.optInt("isdelete");
                                int operstatus = item.optInt("operstatus");//操作状态  0删除 1新增 2修改
                                long timestamp = item.optLong("timestamp");//时间戳
                                String output = item.optString("output");//产量
                                int productTypeId = item.optInt("cid");//基地类型ID 0蔬菜 1肉鸡 2奶牛 3渔业 4生猪
                                int areaId = item.optInt("aid");//所在区的ID
                                String areaName = item.optString("areaName");//所在区的名称
                                String shape = item.optString("shape");//无用
                                String proportion = item.optString("areaSize");//面积;
                                String latitudes = item.optString("latitude");
                                String longitude = item.optString("longitude");
                                BaseBase bb = new BaseBase();
                                bb.setBaseId(baseId);
                                bb.setBaseName(baseName);
                                bb.setBaseAddress(address);
                                bb.setAreaId(areaId);
                                bb.setProductTypeId(productTypeId);
                                bb.setContacts(contacts);
                                bb.setTel(tel);
                                bb.setEmail(email);
                                bb.setProportion(proportion);
                                bb.setOutPut(output);
                                bb.setQuarter("");//季度
                                bb.setExpectedDate("");
                                bb.setExpectedOutPut("");
                                bb.setTheeirAbility("");
                                bb.setType(productTypeId);
                                bb.setFlag(flag + "");
                                bb.setCreateDate(cteatetime);//上报时间
                                bb.setTimeStamp(timestamp);
                                bb.setOperationsTatus(operstatus);
                                bb.setLatitudes(latitudes);
                                bb.setLongitudes(longitude);
                                bb.setBusinessLicence(businessLicence);
                                bb.setIsDelete(isDelete);
                                list.add(bb);
                            }
                            if (null != list && list.size() > 0) {
                                resultList.addAll(list);
                                Message message = new Message();
                                message.what = UPLOAD_SUCCESS;
                                handler.sendMessage(message);
                            } else {//无数据返回

                            }

                        } else {//无数据返回

                        }

                    } else {//更新基地信息时服务器数据异常
                        Message message = new Message();
                        message.what = SERVICE_ERROR;
                        handler.sendMessage(message);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                    Message message = new Message();
                    message.what = JSON_DATA_ERROR;
                    handler.sendMessage(message);
                }
            }
        });

    }

    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case UPLOAD_SUCCESS:
                    new UpdateDBTask().execute();
                    break;
                case UPLOAD_FAIL:
                    break;
                case SERVICE_ERROR:
                    T.showShort(mContext, R.string.service_error);
                    break;
                case JSON_DATA_ERROR:
                    T.showShort(mContext, R.string.service_data_error);
                    break;
            }
        }
    };

    class UpdateDBTask extends AsyncTask<String, Integer, Integer> {

        private final int UPDATE_SUCCESS = 100;
        private final int UPDATE_FAIL = 200;
        private DbManager db;

        @Override
        protected void onPostExecute(Integer integer) {
            super.onPostExecute(integer);
            showDialog.dismissLoadDialog();
            mUpdateResult.onPostExecute(integer);
//            switch (integer) {
//                case UPDATE_SUCCESS:
//                    T.showShort(mContext, R.string.update_ok);
//                    break;
//                case UPDATE_FAIL:
//                    T.showShort(mContext, R.string.update_fail);
//                    break;
//            }
        }

        @Override
        protected Integer doInBackground(String... params) {
            if (null != resultList && resultList.size() > 0) {
                db = XUtilsDbManager.getInstance();
                for (BaseBase baseBase : resultList) {
                    try {
                        BaseBase b = db.selector(BaseBase.class).where("baseName", "=", baseBase.getBaseName()).and("baseAddress", "=", baseBase.getBaseAddress()).findFirst();
                        if (null != b) {
                            b.setOperationsTatus(-1);
                            db.update(b);
                        } else {
                        }
                    } catch (DbException e) {
                        e.printStackTrace();
                    }
                }
                return UPDATE_SUCCESS;
            } else {
                return UPDATE_FAIL;
            }

        }

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            showDialog.showLoadingDialog(mContext.getString(R.string.updateing_db));
        }


    }

    public interface UpdateResult {
        public void onPostExecute(Integer integer);
    }
}
